#!/usr/bin/python
#-*- coding:utf-8 -*
#django添加数据库用户密码
import sys
import os
from optparse import OptionParser

os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "mysite.settings" )
from accounts.models import User
import hashlib



###编码转移,可以输出中文####
reload(sys)
sys.setdefaultencoding('utf-8')


###%prog表示脚本本身
MSG_USAGE = "%prog [ -u <username>][-p <password>][-t <user_type>][-n <ch_name>][-h <help>]"
MSG_VERSION = "%prog 20140702"

###usage打印用法,version输出版本信息
optParser = OptionParser(usage=MSG_USAGE,version=MSG_VERSION)

###对optParser增加选项
optParser.add_option("-u","--username",action = "store",type = "string",dest = "UserName",help="添加数据库用户名(必填)")
optParser.add_option("-p","--password",action = "store",type = "string",dest = "Password",help="添加数据库密码(必填)")
optParser.add_option("-t","--user_type",action = "store",type = "string",dest = "User_Type",default="1",help="添加用户权限,0为管理员,1为普通,默认为1")
optParser.add_option("-n","--ch_name",action = "store",type = "string",dest = "Ch_Name",help="添加用户中文名")

#fakeArgs = ['-u','leon','-p','123456','-t','a']
options,args = optParser.parse_args()

TYPE = options.User_Type
USERNAME = options.UserName
PASSWORD = options.Password
CHNAME = options.Ch_Name

#User_Type返回不是1或者0则退出
if TYPE not in ('1','0'):
    optParser.print_help()
    sys.exit(1)

#判断参数-u,-p是否为空,返回帮助
args_list = [USERNAME,PASSWORD,CHNAME]
for i in args_list:
    if i is None:
        print '请使用(-h,--help)来获得帮助'
        sys.exit(0)


#User是在accounts中models.py的类,定义了数据库的一些信息,插入用户
#判断用户是否存在
def init():
    CHECK_NAME=User.objects.filter(name=USERNAME)
    if len(CHECK_NAME) > 0:
        print "%s 用户已经存在" % USERNAME
    else:
        u = User(name=USERNAME, password=hashlib.md5(PASSWORD).hexdigest(), user_type=TYPE,ch_name=CHNAME)
        u.save()

if '__main__' == __name__:
    init()
